import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment, { isDate } from 'moment';
import router from 'umi/router';
import Media from 'react-media';
import AntdDatePicker from '@/components/AntdDatePicker';
import AntdInput from '@/components/AntdInput';
import AntdFormItem from '@/components/AntdFormItem';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Collapse,
  DatePicker,
  AutoComplete,
  Button,
} from 'antd';
import prompt from '@/components/Prompt';
import AdButton from '@/components/AdButton';
import { codes } from './utils';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import AntdUpload from '@/components/AntdUpload';
import SearchSelect from '@/components/SearchSelect';
import FileReader from '@/components/FileReader';
import { queryFileList, filterAddFile, filterDeteteFile } from '@/utils/common';
import { columns1 } from '@/pages/Common/common';
import { allDictList } from '@/utils/constans';
import styles from '@/pages/Operate.less';

const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;
const Panel = Collapse.Panel;
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';
@connect(({ tmsOil, common, loading, list }) => ({
  tmsOil,
  list,
  
  // ownCompany: common.ownCompany,
  dictObject: common.dictObject,
  id: tmsOil.id,
  loading: loading.models.tmsOil,
}))
@Form.create()
class UpdateForm extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      fileList: [],
      activeKey: ['1', '2'],
      deleteFileIds: [],
      ownCompany: '',
      vehicleId: '',
      oilType: '',
      oilCardType: '',
      totalPrice: '',
      unitPrice: '',
      oilAmount: '',
      cars: [],
      oilTime: '',
      mileage: '',
      oilCardCus: '',
      disabled: false,
      oilCardNo: '',
      oilCardId: '',
    };
    this.fileList = [];
  }
  componentDidMount() {
    
    const { match, dispatch } = this.props;
    const ID = match ? match.params.id : '';
    if (ID) {
      this.getSelectDetails(ID);
      this.queryFileList(ID);
    } else {
      this.props.form.resetFields();
    }

    //字典：
    const allDict = [allDictList.currencyType, allDictList.saleCompany, allDictList.oilType];
    allDict.map(v => {
      dispatch({
        type: 'common/querytDictByCode',
        payload: { code: v },
      });
    });
  }

  queryFileList = id => {
    queryFileList({
      props: this.props,
      params: { bizId: id, fileBizType: 'OIL_MANA' },
      callback: data => {
        if (!data) return;
        this.fileList = data;
        this.props.form.setFieldsValue({ fileTokens: data });
      },
    });
  };

  //切换加油方式：
  onChangeType = (value, type) => {
    this.getOilCardList(value, type);
  };

  //油卡下拉数据
  getOilCardList = (value, type, oilCard) => {
    const {
      dispatch,
      form: { setFieldsValue, resetFields },
    } = this.props;
    if (!oilCard) {
      setFieldsValue({ oilCard: '' });
    } else {
    }
    this.setState(
      {
        [type]: value,
        oilCardId: oilCard ? oilCard.oilCardId : '',
        oilCardNo: oilCard ? oilCard.oilCardNo : '',
      },
      () => {
        if (type == 'oilType') return;
        const { oilSite, sellCompanyCode, cars } = this.state;
        let vehicleId = '';
        if (cars && cars.length > 0) {
          vehicleId = cars.map(v => {
            return v.id;
          });
          vehicleId = vehicleId.join(',');
        }
        let params = {};
        params.pageSize = 1000;
        params.vehicleId = vehicleId;
        if (sellCompanyCode) {
          params.sellCompanyCode = sellCompanyCode;
        }
        if (vehicleId) {
          dispatch({
            type: 'tmsOil/oilCardList',
            payload: params,
            callback: data => {
              this.setState({
                oilCardCus: true,
              });
            },
          });
        }
      }
    );
  };
  getValue = values => {
    this.setState(
      {
        cars: values,
        ownCompany: values[0].ownCompanyName,
      },
      () => {
        this.changeHundredConsump(values, 'cars'); //计算油耗
        this.getOilCardList(values, 'cars'); //获取油卡号
      }
    );
  };
  onChangeNum = (value, type) => {
    if (type == 'oilAmount') this.changeHundredConsump(value, type);

    this.setState(
      {
        [type]: value,
      },
      () => {
        //单价 = 总价/加油量
        const { totalPrice, oilAmount } = this.state;
        let unitPrice = '';
        if (totalPrice && oilAmount) {
          unitPrice = (Number(totalPrice) / Number(oilAmount)).toFixed(2);
        }
        this.props.form.setFieldsValue({ price: unitPrice });
      }
    );
  };
  // 计算 本次油耗
  changeHundredConsump = (value, type) => {
    const {
      form: { getFieldsValue, setFieldsValue },
      dispatch,
      match: {
        params: { id },
      },
    } = this.props;
    const { cars } = this.state;

    this.setState(
      {
        [type]: value,
      },
      () => {
        const { mileage, oilTime, oilAmount } = this.state;
        const _oilTime = oilTime ? moment(oilTime).format(dateFormat) : '';
        const param = { mileage, oilAmount, oilTime: _oilTime };
        let vehicleId = '';
        if (id) param.id = id;
        if (cars.length > 0) {
          vehicleId = cars.map(v => {
            return v.id;
          });
          param.vehicleId = vehicleId.join(',');
        }
        // console.log('param', param);
        if (oilTime && oilAmount && mileage && vehicleId) {
          dispatch({
            type: 'tmsOil/calHundredConsump',
            payload: param,
            callback: data => {
              data && setFieldsValue({ avgHundredConsump: data });
            },
          });
        }
      }
    );
  };

  //详情信息：
  getSelectDetails = ID => {
    const { dispatch } = this.props;
    dispatch({
      type: 'tmsOil/selectDetails',
      payload: { id: ID },
      callback: data => {
        if (!data) return;
        const {
          totalFee,
          price,
          oilAmount,
          oilTime,
          mileage,
          oilSiteName,
          oilCardId,
          oilCardNo,
        } = data;
        const unitPrice = price && Number(price) !== 0 ? Number(price).toFixed(2) : 0;
        this.setState(
          {
            cars: [{ id: data.vehicleId }],
            totalPrice: totalFee,
            oilAmount,
            oilTime,
            mileage,
            oilCardId,
            oilCardNo,
          },
          () => {
            this.getOilCardList(oilSiteName, 'sellCompanyCode', { oilCardId, oilCardNo });
          }
        );
        this.setFileList(data.attachments);
        this.props.form.setFieldsValue({ price: unitPrice });
      },
    });
  };
  getSelectList = (type, val) => {
    const { dispatch } = this.props;
    let params = {};
    if (type == 'search') {
      params = val;
    }
    params.currentPage = 1;
    dispatch({
      type: 'tmsOil/selectList',
      payload: params,
    });
  };

  //保存基本信息：
  saveBasicInfo = e => {
    e.stopPropagation();
    const { fileList, deleteFileIds, cars, oilCardId, oilCardNo } = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (err) {
        return;
      }
      const { oilCard, oilTime, fileTokens, ...value } = values;
      //编辑时传入id
      const {
        match: { params },
        dispatch,
      } = this.props;
      if (params.id) {
        value.id = params.id;
        if (deleteFileIds.length > 0) {
          value.deleteFileIds = deleteFileIds;
        }
      }
      //图片：
      value.fileTokens = filterAddFile(fileTokens);
      value.deleteFileIds = filterDeteteFile(fileTokens, this.fileList);
      value.oilCardId = oilCardId;
      value.oilCardNo = oilCardNo;

      //时间：
      value.oilTime = oilTime ? moment(oilTime).format(dateFormat) : '';
      //保存车辆
      if (cars.length > 0) {
        const vehicleId = cars.map(v => {
          return v.id;
        });
        value.vehicleId = vehicleId.join(',');
      } else {
        value.vehicleId = '';
      }

      this.props.dispatch({
        type: 'tmsOil/oilOperate',
        payload: value,
        callback: res => {
          this.queryFileList(res);
          this.setState(preState => ({
            disabled: !preState.disabled,
          }));
          dispatch({
            type: 'tmsOil/selectDetails',
            payload: { id: res },
            callback: data => {
              // data.attachments && this.setFileList(data.attachments);

              this.setState({ cars: [{ id: data.vehicleId }] });
              console.log('params.id',params.id,data)
              if (!params.id) {
                dispatch({
                  type: 'common/setTabsName',
                  payload: {
                    id: res,
                    name: data.oilNo,
                    isReplaceTab: true,
                  },
                  callback: result => {
                    if (result) {
                      router.push(`/carDaily/oilList/edit-form/${res}`);
                    }
                  },
                });
              }
            },
          });
          this.getSelectList();
        },
      });
    });
  };

  // 设置图片
  setFileList = fileList => {
    this.setState({ fileList });
  };

  // 上传图片
  handleChange = fileList => {
    this.setState({ fileList });
  };

  // 删除图片
  onRemove = deleteFileIds => {
    this.setState({
      deleteFileIds,
    });
  };

  callback = key => {
    this.setState({
      activeKey: key,
    });
  };

  oilCardTypeSelectd = oilCardType => {
    this.setState({ oilCardType });
  };

  //自动输入：
  Complete = data => {
    const arr1 = [];
    if (data && data.length > 0) {
      data.map(v => {
        const obj = {};
        obj.value = v.code;
        obj.text = v.value;
        arr1.push(obj);
      });
    }
    const { disabled } = this.state;
    return (
      <AutoComplete
        dataSource={arr1}
        placeholder="请输入"
        filterOption={(inputValue, option) =>
          option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
        }
        onChange={value => {
          this.setState({
            oilSite: value,
            sellCompanyCode: '',
          });
        }}
        disabled={disabled}
        onSelect={(value, option) => {
          this.getOilCardList(value, 'sellCompanyCode');
          this.setState({
            oilSite: option.props.children,
          });
        }}
      />
    );
  };

  changeOilCard = val => {
    this.setState({
      oilCardId: val.split(',')[0],
      oilCardNo: val.split(',')[1],
    });
  };

  render() {
    const { fileList, disabled, ownCompany, oilCardType, unitPrice, oilAmount, cars } = this.state;
    const {
      tmsOil: { oilCardList, selectDetails },
      list: { carList },
      form: { getFieldDecorator },
      dictObject,
      match: { params },
    } = this.props;
    const currentId = params.id;
    const details = selectDetails[currentId] ? selectDetails[currentId] : {};
    const _oilCardType = oilCardType ? oilCardType : details.oilType || '';
    console.log('_oilCardType--',_oilCardType,oilCardList.list )
    const vehicleList = [];
   

    const genExtraBasicInfo = () => (
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <span>{details && currentId ? details.oilNo : '新增加油'}</span>
        {disabled ? (
          <AdButton
            type="primary"
            onClick={() => {
              this.setState(preState => ({
                disabled: !preState.disabled,
              }));
            }}
            text="编辑"
            code={details && currentId ? codes.edit : codes.add}
          />
        ) : (
            <Button.Group>
              <AdButton
                type="primary"
                onClick={e => this.saveBasicInfo(e)}
                text="保存"
                code={details && currentId ? codes.edit : codes.add}
              />
              {details && currentId && (
                <AdButton
                  onClick={() => {
                    this.setState(preState => ({
                      disabled: !preState.disabled,
                    }));
                  }}
                  text="取消"
                  code={details && currentId ? codes.edit : codes.add}
                />
              )}
            </Button.Group>
          )}
      </div>
    );
    const customPanelStyle = {
      borderRadius: 4,
      marginBottom: 12,
      border: 0,
      overflow: 'hidden',
    };
    const prefixSelector = getFieldDecorator('currencyType', {
      initialValue: details && details.currencyType ? details.currencyType : 'CNY',
    })(
      <Select placeholder="请选择" style={{ width: 90 }} disabled={disabled}>
        {dictObject[allDictList.currencyType] &&
          dictObject[allDictList.currencyType].map(item => (
            <Option key={item.code}>{item.value}</Option>
          ))}
      </Select>
    );
    return (
      <div className={styles.CollapseUpdate}>
        <PageHeaderWrapper title={this.props.type == 'add' ? '加油新建' : genExtraBasicInfo()}> 
          <Collapse
            activeKey={this.state.activeKey}
            onChange={key => this.callback(key)}
            bordered={false}
          >
            <Panel header="基础信息" key="1" style={customPanelStyle}>
              <div className={styles.tableListForm}>
                <Form layout="inline">
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={12} sm={24}>
                      <Form.Item label="单据号码">
                        {getFieldDecorator('oilNo', {
                          initialValue: details ? details.oilNo : '保存后系统自动生成',
                        })(<Input placeholder="保存后系统自动生成" disabled />)}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={12} sm={24}>
                      <Form.Item label="车牌号">
                        {getFieldDecorator('vehicleId', {
                          rules: [{ required: true, message: '请输入车牌号' }],
                          initialValue: details ? details.vehicleId : '',
                        })(
                          <SearchSelect
                            dataUrl="tms/tms-oil/selectOilVehicle"
                            url="tms/tms-oil/selectOilVehicleView_s" // selectedData只只有id时需要传url
                            selectedData={cars} // 选中值
                            multiple={false} // 是否多选
                            showValue="cartPlateOneNo"
                            searchName="cartPlate"
                            columns={columns1} // 表格展示列
                            onChange={this.getValue} // 获取选中值
                            scrollX={480}
                            disabled={details && currentId  ?true:false}
                            id="tmsOil_2"
                          />
                        )}
                      </Form.Item>
                    </Col>
                    <Col md={12} sm={24}>
                      <Form.Item label="所属公司">
                        {getFieldDecorator('ownCompanyName', {
                          initialValue: ownCompany ? ownCompany : details && details.ownCompanyName,
                        })(<Input placeholder="请输入所属公司" disabled={true} />)}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                  <Col md={12} sm={24}>
                      <Form.Item label="行车档案号" >
                        {getFieldDecorator('archivesNo', {
                          initialValue: details ? details.archivesNo : '保存后系统自动生成',
                        })(<Input placeholder="" disabled />)}
                      </Form.Item>
                    </Col>
                    <Col md={12} sm={24}>
                      <Form.Item label="结算周期">
                        {getFieldDecorator('settlementDate', {
                          initialValue: details ? details.settlementDate : '保存后系统自动生成',
                        })(<Input placeholder="" disabled />)}
                      </Form.Item>
                    </Col>
                  </Row>
                </Form>
              </div>
            </Panel>
            <Panel header="费用详情" key="2" style={customPanelStyle}>
              <div className={styles.tableListForm}>
                <Form layout="inline">
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={12} sm={24}>
                      <Form.Item label="加油站名称">
                        {getFieldDecorator('oilSiteName', {
                          initialValue: details ? details.oilSiteName : '',
                        })(
                          // this.Complete(dictObject[allDictList.saleCompany])

                          <Select
                            disabled={disabled}
                            placeholder="请选择"
                            onSelect={this.oilCardTypeSelectd}
                            onChange={(value, option) => {
                              this.getOilCardList(value, 'sellCompanyCode');
                              this.setState({
                                oilSite: option.props.children,
                              });
                            }}
                          >
                            <Option value="">请选择</Option>
                            {dictObject[allDictList.saleCompany] &&
                              dictObject[allDictList.saleCompany].map(item => (
                                <Option key={item.code}>{item.value}</Option>
                              ))}
                          </Select>
                        )}
                      </Form.Item>
                    </Col>
                    <Col md={12} sm={24}>
                      <Form.Item label="加油方式">
                        {getFieldDecorator('oilType', {
                          rules: [{ required: true, message: '请输入加油方式' }],
                          initialValue: details ? details.oilType : undefined,
                        })(
                          <Select
                            disabled={disabled}
                            placeholder="请选择"
                            onSelect={this.oilCardTypeSelectd}
                            onChange={(value, options) => this.onChangeType(value, 'oilType')}
                          >
                            {dictObject[allDictList.oilType] &&
                              dictObject[allDictList.oilType].map(item => (
                                <Option key={item.code}>{item.value}</Option>
                              ))}
                          </Select>
                        )}
                      </Form.Item>
                    </Col>
                  </Row>

                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={12} sm={24}>
                      <Form.Item label="油卡号">
                        {getFieldDecorator('oilCard', {
                          rules: [
                            {
                              required: _oilCardType == 'CARD'||_oilCardType === 'OIL-MONTHLYBALANCE' ? true : false,
                              message: '请输入油卡号',
                            },
                          ],
                          initialValue: details ? details.oilCardNo : undefined,
                        })(
                          <Select
                            showSearch
                            filterOption={(input, option) =>
                              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                            placeholder="请选择"
                            style={{ width: '100%' }}
                            allowClear={true}
                            disabled={disabled||_oilCardType == 'CASH'}
                            onChange={this.changeOilCard}
                          >
                            <Option value="">请选择</Option>
                            {oilCardList.list &&
                              oilCardList.list.map((v, i) => {
                                return (
                                  <Option key={i} value={`${v.id},${v.cardNo}`}>
                                    {v.cardNo}
                                  </Option>
                                );
                              })}
                          </Select>
                        )}
                      </Form.Item>
                    </Col>
                    <Col md={12} sm={24}>
                      <Form.Item label="加油时间">
                        {getFieldDecorator('oilTime', {
                          rules: [{ required: true, message: '请输入加油时间' }],
                          initialValue:
                            details && details.oilTime
                              ? moment(details.oilTime, dateFormat)
                              : undefined,
                        })(
                          <AntdDatePicker
                            disabled={disabled}
                            onChange={e => this.changeHundredConsump(e, 'oilTime')}
                          />
                        )}
                      </Form.Item>
                    </Col>
                  </Row>

                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={12} sm={24}>
                      <Form.Item label="加油人">
                        {getFieldDecorator('oilPerson', {
                          rules: [{ required: true, message: '' }],
                          initialValue: details ? details.oilPerson : '',
                        })(<Input placeholder="请输入" disabled={disabled} />)}
                      </Form.Item>
                    </Col>
                    <Col md={12} sm={24}>
                      <Form.Item label="当前里程(KM)">
                        {getFieldDecorator('mileage', {
                          rules: [{ required: true, message: '' }],
                          initialValue: details ? details.mileage : '',
                        })(
                          <AntdInput
                            // mode="money"
                            disabled={disabled}
                            mode="anyNumber"
                            placeholder="请输入当前里程"
                            onChange={e => this.changeHundredConsump(e, 'mileage')}
                          />
                        )}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={12} sm={24}>
                      <AntdFormItem
                        label="加油量(升)"
                        code="oilAmount"
                        rules={[{ required: true, message: '请输入' }]}
                        initialValue={details ? details.oilAmount : ''}
                        getFieldDecorator={getFieldDecorator}
                      >
                        <AntdInput
                          mode="money"
                          disabled={disabled}
                          label="加油量(升)"
                          placeholder="长度不超过18位可保留两位小数"
                          onChange={e => this.onChangeNum(e, 'oilAmount')}
                        />
                      </AntdFormItem>
                    </Col>
                    <Col md={12} sm={24}>
                      <AntdFormItem label="单价" code="price" getFieldDecorator={getFieldDecorator}>
                        <AntdInput disabled />
                      </AntdFormItem>
                    </Col>
                  </Row>
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={12} sm={24}>
                      <AntdFormItem
                        label="总金额"
                        code="totalFee"
                        rules={[{ required: true, message: '请输入' }]}
                        getFieldDecorator={getFieldDecorator}
                        initialValue={
                          details && details.totalFee
                            ? Number(details.totalFee) !== 0
                              ? Number(details.totalFee).toFixed(2)
                              : 0
                            : ''
                        }
                      >
                        <AntdInput
                          mode="money"
                          disabled={disabled}
                          label="总金额"
                          placeholder="长度不超过18位可保留两位小数"
                          addonBefore={prefixSelector}
                          onChange={e => this.onChangeNum(e, 'totalPrice')}
                        />
                      </AntdFormItem>
                    </Col>
                    <Col md={12} sm={24}>
                      <Form.Item label="本次油耗">
                        {getFieldDecorator('avgHundredConsump', {
                          initialValue: details ? details.avgHundredConsump : '',
                        })(<Input disabled />)}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={24}>
                      <Form.Item label="备注">
                        {getFieldDecorator('remarks', {
                          initialValue: details ? details.remarks : '',
                        })(<TextArea rows={4} disabled={disabled} />)}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={24}>
                      <Form.Item label="票据">
                        {getFieldDecorator('fileTokens')(
                          <FileReader disabled={disabled} urlType="tms" />
                        )}
                      </Form.Item>
                    </Col>
                  </Row>
                </Form>
              </div>
            </Panel>
          </Collapse>
        </PageHeaderWrapper>
      </div>
    );
  }
}
export default UpdateForm;
